import { app, shell, BrowserWindow, ipcMain, dialog } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import { randomUUID } from 'crypto'
import path from 'path'
import fs from 'fs'
import { spawn } from 'child_process'
import icon from '../../resources/pic/icon.png?asset'
import Store from 'electron-store'

// 初始化config
const config = new Store({ name: 'config' })
if (!config.size) {
  // size 为 0 表示没有任何 key
  config.store = {} // 或 config.store = [] 看你要顶层对象还是数组
}
if (!config.has('preset')) config.set('preset', {})
if (!config.has('components')) config.set('components', [])

// 获取应用打包后文件夹路径
function getPath(basename) {
  let origin = app.isPackaged ? process.resourcesPath : path.resolve(__dirname, '../../')
  const _path = {
    // eslint-disable-next-line prettier/prettier
    root:origin,
    lib: path.resolve(origin, 'lib'),
    res: path.resolve(origin, 'resources'),
    tmp: path.resolve(origin, 'tmp')
  }
  return basename ? _path[basename] : origin
}

// 创建初始为空的文件夹
if (!fs.existsSync(getPath('tmp'))) fs.mkdirSync(getPath('tmp'), { recursive: true });

// 执行工具
function useTool(name, options) {
  // path 可执行文件的名称
  // options 附带的命令行参数
  options = options || []
  // console.log("options:",options);

  return new Promise((resolve, reject) => {
    const exePath = path.join(getPath('lib'), name) // 获取可执行文件的完整
    if (!fs.existsSync(exePath + '.exe')) {
      reject({
        status: 'error',
        data: `${name} 不存在` // 此处附带的信息如何获取
      })
    }
    const child = spawn(exePath, options)
    const result = []

    child.stdout.on('data', (data) => {
      result.push(data.toString())
    })

    child.on('close', (code) => {
      // resolve(`工具运行完成，退出码: ${code}\n输出内容:${result.join('\n')}`);
      resolve({
        code,
        status: code === 0 ? 'success' : 'error',
        data: result.join('\n')
      })
    })

    child.on('error', (err) => {
      reject({
        status: 'error',
        data: err
      })
    })
  })
}

function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 900,
    height: 670,
    show: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  // 自动打开开发者工具
  // mainWindow.webContents.openDevTools({ mode: 'undocked' })
  // mode 可以是 'right', 'bottom', 'undocked', 'detach'

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  // ipcMain.on('ping', () => {
  //   publicConfig.ip = 'pong'
  // })

  // HANDLE
  // ipcMain.handle('ip', getLocalIp)

  // =====================================================================================================================

  // 打开自定义文件夹
  ipcMain.handle('open-folder', (event, payload) => {
    if (!payload.path) return { code: -1, message: '没有目录路径数据', path: payload.path }
    if (!fs.existsSync(payload.path)) return { code: -1, message: '文件不存在' }
    payload.type === 'file' ? shell.showItemInFolder(payload.path) : shell.openPath(payload.path)
    return { code: 0, message: '成功' }
  })

  // 打开config目录
  ipcMain.handle('open-config-folder', () => {
    shell.showItemInFolder(config.path)
  })
  // 获取config数据
  ipcMain.handle('get-config', (event, key) => {
    return config.get(key, [])
  })
  // 修改config数据
  ipcMain.handle('set-config', (event, key, value) => {
    return config.set(key, value)
  })
  // 删除config数据
  ipcMain.handle('delete-config', (event, key) => {
    return config.delete(key)
  })

  // 运行工具
  ipcMain.handle('use-tool', async (event, payload) => {
    // console.log(payload)
    const result = await useTool(payload.name, payload.data)
    result['uuid'] = payload.uuid
    // fs.unlinkSync(_p)
    return result
  })

  // 保存文件
  ipcMain.handle('save-docx', async (event, payload) => {
    const _p = path.join(getPath('tmp'), `${randomUUID()}.json`) // 创建临时参数文件
    fs.writeFileSync(_p, JSON.stringify(payload || []))
    const { data: file_path } = await useTool('core/save', [_p])
    fs.unlinkSync(_p) // 删除临时参数文件
    // 打开保存文件功能
    const result = await dialog.showSaveDialog(BrowserWindow.getFocusedWindow(), {
      defaultPath: '题名.docx',
      filters: [{ name: 'Word 文档', extensions: ['docx'] }]
    })

    if (result.canceled) {
      fs.unlinkSync(file_path)
      return { canceled: true }
    }

    fs.copyFileSync(file_path, result.filePath)
    fs.unlinkSync(file_path) // 删除生成的docx文件
    return { canceled: false, savePath: result.filePath }
  })

  // =====================================================================================================================

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
